<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;    
use fast\Random;

/**
 * 手机短信接口
 */
class Sms extends Api  
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 马来西亚bulk360短信发送
     */
    public function send()
    {
        $mobile = input('post.mobile');

        if (substr($mobile, 0, 2) != '60' && substr($mobile, 0, 3) != '852' && substr($mobile, 0, 2) != '65') {
            $this->error('Unauthorized TAC request detected.');
        }

        $event = 'mobilelogin';
        if (strlen($mobile) <= 3 || !ctype_digit($mobile)) {
            $this->error('The phone number entered is incorrect. Please verify and try again.');
        }
        $last = Smslib::get($mobile, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('You have requested the verification code too many times. Please wait a moment and try again.'));
        }
        $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('You have requested the OTP too many times. Please try again later.'));
        }

        $code = Random::numeric(config('captcha.length'));
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);
        if ($sms) {
            $user = urlencode('MVyb8DLbvA');
            $pass = urlencode('Q6acs8Zr9FkbMlpxUCeCzypxUZizOMBUj9TKt9Bk');
            $from = 'FOODINCE';
            $url = 'https://sms.360.my/gw/bulk360/v3_0/send.php';
            $end_url = $url . '?user=' . $user . '&pass=' . $pass . '&form=' . $from;

            $text = 'Uncle Five Coffee: Thanks for using Uncle Five Coffee mobile app. Your verification code is ' . $code . '. Do not share your verification code with others.';

            $sen_url = $end_url . "&to=" . $mobile . "&text=" . rawurlencode($text);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $sen_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $sentResult = curl_exec($ch);
            if ($sentResult == FALSE) {
                echo 'Curl failed for sending sms to bulk360.. ' . curl_error($ch);
            }
            curl_close($ch);
        }
        $this->success('Success');
    }


    /**
     * 马来西亚bulk360短信平台回调
     */
    public function bulk_notify()
    {
        $data = file_get_contents('php://input');
        \think\Log::record('咖啡馆短信平台回调' . json_encode($data, 256));
//        $result = json_decode($data, true);
        echo 'SUCCESS';
    }

}